package cn.geminis.lowcode.processor;

import cn.geminis.lowcode.annotation.SoftDeleteEntity;
import cn.geminis.lowcode.compiler.code.LcAnnotation;
import cn.geminis.lowcode.compiler.code.LcClass;
import cn.geminis.lowcode.compiler.code.LcModifier;
import cn.geminis.lowcode.compiler.code.LcVariable;
import cn.geminis.lowcode.utils.Flags;
import cn.geminis.lowcode.utils.Utils;

import javax.lang.model.element.Element;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Map;
import java.util.stream.Stream;

/**
 * @author puddi
 */
public class SoftDeleteEntityProcessor implements BaseProcessor {

    @Override
    public Class<? extends Annotation> getSupportAnnotation() {
        return SoftDeleteEntity.class;
    }

    @Override
    public void process(Element element) {
        var annotation = element.getAnnotation(SoftDeleteEntity.class);
        var entityClass = new LcClass(element);
        addDeleteField(entityClass, annotation);

        Utils.noteMessage(Utils.getElementQualifiedName(element) + " deleted Enhanced");
    }

    private void addDeleteField(LcClass entity, SoftDeleteEntity annotation) {
        var annotations = new ArrayList<>(Stream.of(annotation.deleteFieldAnnotations()).map(LcAnnotation::new).toList());
        annotations.add(new LcAnnotation(
                "jakarta.persistence.Column",
                Map.of("nullable", false)
        ));
        annotations.add(new LcAnnotation("cn.geminis.lowcode.annotation.QueryFilterProperty"));
        var deletedField = new LcVariable(
                new LcModifier(
                        Flags.PRIVATE,
                        annotations.toArray(new LcAnnotation[0])
                ),
                "BOOLEAN",
                "deleted"
        );
        entity.append(deletedField);
    }
}
